import { reactive, toRaw, ref } from 'vue'

// 分页钩子函数
interface Options {
    page?: number
    size?: number
    fetchFun: (_arg: any) => Promise<any>
    params?: Record<any, any>
    firstLoading?: boolean
    autoResetPage?: boolean // 添加自动重置页码的开关
}

export function usePaging(options: Options) {
    const { 
        page = 1, 
        size = 10, 
        fetchFun, 
        params = {}, 
        firstLoading = false,
        autoResetPage = true // 默认启用自动重置页码
    } = options
    
    // 记录分页初始参数
    const paramsInit: Record<any, any> = Object.assign({}, toRaw(params))
    
    // 记录上次搜索的参数
    const lastSearchParams = ref(Object.assign({}, toRaw(params)))

    // 分页数据
    const pager = reactive({
        page,
        size,
        loading: firstLoading,
        count: 0,
        lists: [] as any[]
    })

    // 比较参数是否发生变化
    const isParamsChanged = () => {
        const currentParams = toRaw(params)
        return Object.keys(currentParams).some(
            key => currentParams[key] !== lastSearchParams.value[key]
        )
    }

    // 请求分页接口
    const getLists = () => {
        // 只有在启用自动重置且参数发生变化时，才重置页码
        if (autoResetPage && isParamsChanged()) {
            pager.page = 1
        }

        // 每次调用都更新上次搜索参数
        Object.assign(lastSearchParams.value, toRaw(params))

        pager.loading = true
        return fetchFun({
            pageNo: pager.page,
            pageSize: pager.size,
            ...params
        })
            .then((res: any) => {
                pager.count = res?.count
                pager.lists = res?.lists
                return Promise.resolve(res)
            })
            .catch((err: any) => {
                return Promise.reject(err)
            })
            .finally(() => {
                pager.loading = false
            })
    }
    // 重置为第一页
    const resetPage = () => {
        pager.page = 1
        getLists()
    }
    // 重置参数
    const resetParams = () => {
        Object.keys(paramsInit).forEach((item) => {
            params[item] = paramsInit[item]
        })
        Object.assign(lastSearchParams.value, paramsInit)
        getLists()
    }
    return {
        pager,
        getLists,
        resetParams,
        resetPage
    }
}
